import os
import sqlite3


class Handler(object):

    def __init__(self,db_path):
        super(Handler, self).__init__()
        self.db_path = db_path

        db_dir = os.path.dirname(self.db_path)
        if not os.path.exists(db_dir):
            os.makedirs(db_dir)
        self.conn = sqlite3.connect(self.db_path)
        self.cursor = self.conn.cursor()
        # self.init_table()

    def init_table(self):

        sql = '''
        create table if not exists task(
        id int primary key ,
        cg_id varchar(200) not null,
        database varchar(100) not null,
        project varchar(100) not null,
        asset_shot_name varchar(200) not null,
        dir varchar(200) not null)
        '''
        self.cursor.execute(sql)
        self.conn.commit()

    def save_task(self,task_data):
        sql ="replace into task(cg_id,database,project,asset_shot_name,dir) values " \
             "('{0}','{1}','{2}','{3}','{4}') ".format(task_data['cg_id'],task_data['database'],
                                                                         task_data['entity_name'],task_data['asset_shot'],task_data['dir'])

        self.cursor.execute(sql)
        self.conn.commit()

    def select_task(self,cg_id):
        sql = "select cg_id,database,project,asset_shot_name,dir from task where cg_id ='{}'".format(cg_id)
        self.cursor.execute(sql)
        result = self.cursor.fetchone()
        # if result:
        print(result)

    def get_all_task(self):
        sql = "select * from task "
        self.cursor.execute(sql)
        result = self.cursor.fetchall()
        if result:
            for i in result:
                print(i)


    def close(self):
        self.conn.close()



if __name__ == '__main__':
    db_path = r'C:\timeaxis_my_task\db\local_task_info.db'
    handler = Handler(db_path)
    handler.get_all_task()
    handler.close()